import { Injectable } from '@angular/core';

import { HttpClient,HttpHeaders } from '@angular/common/http'
import { StorageService } from './storage.service'
import { AlertController,ToastController } from '@ionic/angular';
import { Router } from '@angular/router'
import { environment } from '../../environments/environment'

@Injectable({
  providedIn: 'root'
})
export class CommonService {

  // 配置域名
  // public config:any = 'http://47.104.254.67'
  // public config:any = 'http://124.70.138.12:9001'
  public config:string = environment.baseUrl;
  // public configs:string = 'http://testhxys.hengxunyun.com';
  public configs:string = 'http://hxystorage.hengxunyun.com';
  // environment.baseUrl

  
  
  constructor(private http:HttpClient,private storage:StorageService,public alertController: AlertController,private router:Router,private toastController:ToastController) {
    console.log(this.config)
  }

  // 封装http服务接口
  get(url){
    var token = null
    if(this.storage.get('userInfo') !== null){
      token = this.storage.get('userInfo').token
    }
    var httpOptions = {headers: new HttpHeaders({'Content-Type': 'application/json', 'Accept': '*/*','deviceId':this._IsDevice(),'token':token})}

    var api = this.config + url
    return new Promise((resove,reject)=>{
      this.http.get(api,httpOptions).subscribe((response)=>{
        resove(response)
      },(err)=>{
        reject(err)
      })
    })
  }

  post(url,params,boolean:boolean){
    var token = null
    if(this.storage.get('userInfo') !== null){
      token = this.storage.get('userInfo').token
    }
    // 传表头，传参数
    var httpOptions = boolean?{ 
      headers: new HttpHeaders({'Content-Type': 'application/json', 'Accept': '*/*','deviceId':this._IsDevice()}),
      params:params
    }:{ 
      headers: new HttpHeaders({'Content-Type': 'application/json', 'Accept': '*/*','deviceId':this._IsDevice(),'token':token}),
      params:params
    }

    var api = this.config + url
    return new Promise((resove,reject)=>{
      this.http.post(api,null,httpOptions).subscribe((response)=>{
        resove(response)
        // if(response.code != '200'){
        //   console.log(response)
        //   if(response.msg == "登录超时或已在其他设备登录，请重新登录！"){
        //     this.presentAlert(response.msg)
        //     this.router.navigateByUrl("login")
        //   }
        // }
      },(err)=>{
        reject(err)
      })
    })
  }

  postbodys(url,body){
    var token = null
    if(this.storage.get('userInfo') !== null){
      token = this.storage.get('userInfo').token
    }
    // 传表头，传参数
    var httpOptions = { 
      headers: new HttpHeaders({'Content-Type': 'application/json', 'Accept': '*/*','deviceId':this._IsDevice(),'token':token})
    }

    var api = this.config + url
    return new Promise((resove,reject)=>{
      this.http.post(api,body,httpOptions).subscribe((response)=>{
        resove(response)
      },(err)=>{
        reject(err)
      })
    })
  }

  postbody(url,body){
    // 传表头，传参数
    var httpOptions = { 
      headers: new HttpHeaders({'token':this.storage.get('userInfo').token, 'Accept': '*/*','webFlag':'webFlag'}),
    }

    var api = this.config + url
    return new Promise((resove,reject)=>{
      this.http.post(api,body,httpOptions).subscribe((response)=>{
        resove(response)
      },(err)=>{
        reject(err)
      })
    })
  }

  // 传ID更新储存
  getIdInfo(){
      // 获取登录信息
      var api = '/tbr/getUserInfo'
      var params = {'userId': this.getInfo().userId}
      
      this.post(api,params,false).then((response:any)=>{
        if(response.code == 200){
          // console.log('传ID更新储存')
          this.storage.set('PersonalInfo',response.data)
        }
      })
  }

  // 获取用户基本信息
  getInfo(){
    var userinfo=this.storage.get('PersonalInfo');

    if(userinfo.avater == '' || userinfo.avater == null){
      userinfo.avater = 'assets/avater.png'
    }
    
    if(userinfo && userinfo.nickname){
      return userinfo
    }else{
      return userinfo=null;
    } 
    // console.log(userinfo)
  }


  // 手机验证
  yzShouJi(value){
    if (value === '') {
      this.presentAlert("手机不可为空")
      return false
    }else if(value !== '') {
      var reg= /^1[3456789]\d{9}$/;
      if(!reg.test(value)){
        this.presentAlert('请输入有效的手机号码');
        return false
      }else return true
    }
  }

  //姓名
  yzName(value){
    //Unicode编码中的汉字范围
    if (value === '') {
      this.presentAlert("姓名不可为空")
      return false
    }else if(value !== '') {
      var reg= /^[\u2E80-\u9FFF]+$/;
      if(!reg.test(value)){
        this.presentAlert('姓名输入不合法');
        return false
      }else return true
    }
  }

  yzCode(value){
    // 身份证正则表达
    if (value === '') {
      this.presentAlert("身份证不可为空")
      return false
    }else if(value !== '') {
      var reg= /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
      if(!reg.test(value)){
        this.presentAlert('请输入有效的身份证');
        return false
      }else return true
    }
  }

  bankCard(value){
    // 银行卡号校验
    if (value === '') {
      this.presentAlert("银行卡号不可为空")
      return false
    }else if(value !== '') {
      var reg= /^([1-9]{1})(\d{15}|\d{18})$/; 
      if(!reg.test(value)){
        this.presentAlert('请输入有效的身份证');
        return false
      }else return true
    }
  }
  // regTest(value){
  //   2 var regExp = 
  //   3 return regExp.test(data) 
  //   4 } 
  //   5 console.log('regTest(): ', test('6210812470004250007')); 
  // }

  // 判断是否为ios端访问 或者 Android
 _IsDevice () {
  if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
    return '7'
  } else if(/(Android)/i.test(navigator.userAgent)){
    return '8'
  }else{
    return '9'
  }
}


  // 弹出框
  async presentAlert(message:string) {
    const alert = await this.alertController.create({
        // cssClass: 'my-custom-class',
        header: '提示',
        // subHeader: 'Subtitle',
        message: message,
        buttons: [
          {
            text: '确定',
            handler: (blah) => {
              if(message == '登录超时或已在其他设备登录，请重新登录！'){
                this.storage.remove('userInfo')
                this.storage.remove('PersonalInfo')
                this.router.navigateByUrl('login')
              }
              // console.log('Confirm Cancel: blah');
            }
          }
        ]
    });
    await alert.present();
  }

  // 弹出框
  async presentAlertUrl(message:string,url:string) {
    const alert = await this.alertController.create({
        // cssClass: 'my-custom-class',
        header: '提示',
        // subHeader: 'Subtitle',
        message: message,
        buttons: [
          {
            text: '取消',
            role: 'cancel'
          },
          {
            text: '确定',
            handler: (blah) => {
                this.router.navigateByUrl(url)
            }
          }
        ]
    });
    await alert.present();
  }

   // 弹窗
   async presentToast(msg:string) {
    const toast = await this.toastController.create({
      message: msg,
      mode:'md',
      position:'bottom',
      duration: 1500,
      color: 'darks'
    });
    toast.present();
  }

  //复制
  Clipboard = (function(window, document, navigator) {
    
    var textArea,
        copy;
    // 判断是不是ios端
    function isOS() {
      return navigator.userAgent.match(/ipad|iphone/i);
    }
    //创建文本元素
    function createTextArea(text) {
      textArea = document.createElement('textArea');
      textArea.innerHTML = text;
      textArea.value = text;
      document.body.appendChild(textArea);
    }
    //选择内容
    function selectText() {
      var range,
          selection;
  
      if (isOS()) {
        range = document.createRange();
        range.selectNodeContents(textArea);
        selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);
        textArea.setSelectionRange(0, 999999);
      } else {
        textArea.select();
      }
    }
    
    // var _this = this
    
  //复制到剪贴板
  function copyToClipboard() {        
      try{
        if(document.execCommand("Copy")){
          alert("复制成功！"); 
        }else{
          alert("复制失败！请手动复制！");
        }
      }catch(err){
        alert("复制错误！请手动复制！")
      }
      document.body.removeChild(textArea);
    }
  
    copy = function(text) {
      createTextArea(text);
      selectText();
      copyToClipboard();
    };
  
    return { 
      copy: copy
    };
    
  })(window, document, navigator);
}
